package com.xltt.watchfota;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Environment;
import android.os.PowerManager;
import android.os.StatFs;
import android.provider.Settings;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.io.IOException;

public class BaseActivity extends AppCompatActivity {
    public static final String TAG = "zhanghui";

    /**
     * 获取系统版本号
     * @return
     */
    public String getSystemVersion() {
        return android.os.SystemProperties.get("ro.build.display.version");
    }


    /**
     * 获取当前设备电量
     * @return
     */
    public int getBatteryLevel(){
        return mBatteryLevel;
    }

    /**
     * 获取设备内部存储空空间
     * @return
     */
    public long getAvailMemoryLong() {
        File sdcardDir = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(sdcardDir.getPath());
        long blockSize = sf.getBlockSizeLong();
        long availCount = sf.getAvailableBlocksLong();
        Log.d(TAG, "getAvailMemoryLong: blockSize * availCount = " + blockSize + " * " + availCount + " = " + blockSize * availCount);
        return blockSize * availCount;
    }

    /**
     * 根据文件大小判断存储空间是否可使用
     * @param length
     * @return
     */
    public boolean isMemoryEnough(double length) {
        boolean result = true;
        long min = 1024 * 1024 / 2;
        long max = 1024 * 1024 * 50;
        long freeMemory = getAvailMemoryLong();
//        Log.e(TAG, "isMemoryEnough: getAvailMemoryLong() = " + getAvailMemoryFormat() + "  " + getAvailMemoryLong());
        if (freeMemory < (length + min)) {
            Log.e(TAG, "isMemoryEnough:  low memory");
            // 提醒 内存太少，不够下载了
//            handler.removeCallbacks(runnableWifi);
//            initFloatView(MemoryLow, 0, false);
            result = false;
//            INotification.getInstance().notifyService(this, getReDownloadIntent(), getString(R.string.update_notification) + ":", getString(R.string.cleanover_updatecontinue));
        } else if (freeMemory < (length + max)) {
            //需要提醒内存不足了
            //发个消息通知栏
//            INotification.getInstance().notify(this, getFileManagerIntent(), "升级提示：内存不足", "请清理空间，方便下载升级包");
            Log.w(TAG, "isMemoryEnough:  内存不足，处于临界线< length + Max");
        } else {
            Log.i(TAG, "isMemoryEnough:  取消通知");
//            INotification.getInstance().cancel(this);
        }
        Log.i(TAG, "isMemoryEnough: result = " + result);
        return result;
    }


    public void initBatteryInfo(Context context){
        context.registerReceiver(mBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    public void destroyBatteryInfo(Context context){
        context.unregisterReceiver(mBatteryInfoReceiver);
    }

    private int mBatteryLevel = 0;
    private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                mBatteryLevel = intent.getIntExtra("level", 0);
                Log.d(TAG, "当前电量 = " + mBatteryLevel);
            }
        }
    };

    /**
     * 文件权限
     * @param file
     */
    public void fileCommand(File file){
        file.setReadable(true, false);
        file.setWritable(true, false);
        file.setExecutable(true, false);
        try {
            String command = "chmod 777 " + file.getAbsolutePath();
            Log.i("zhanghui", "command = " + command);
            Runtime runtime = Runtime.getRuntime();

            Process proc = runtime.exec(command);
        } catch (IOException e) {
            Log.i("zhanghui", "chmod fail!!!!");
            e.printStackTrace();
        }
    }

    private static final String HOST_TEST = "http://59.44.43.234:60124/";//测试环境
    private static final String HOST = "http://202.165.22.244:50010/";//QA环境
    private static final String API = "watch/fota/getAvailbleVersion";//接口

    /**
     * 获取接口地址
     * @return
     */
    public String getHost(){
        int address = Settings.Global.getInt(getContentResolver(),"watch_fota_host",0);
        if(address == 0){//测试环境
            return HOST_TEST + API;
        }
        return HOST + API;
    }

    private PowerManager.WakeLock mWakeLock = null;
    /**
     * 获取唤醒锁
     */
    public void acquireWakeLock() {
        if(mWakeLock == null) {
            PowerManager mPM = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            mWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|
                    PowerManager.ON_AFTER_RELEASE,"watch_fota");
            if(mWakeLock!=null) {
                Log.d(TAG, "获取wakelock休眠锁");
                mWakeLock.acquire();
            }
        }
    }

    /**
     * 释放锁
     */
    public void releaseWakeLock() {
        if(mWakeLock!=null) {
            Log.d(TAG, "释放wakelock锁");
            mWakeLock.release();
            mWakeLock = null;
        }
    }

}
